package examsrv

import (
	"strings"

	"gitee.com/chuanjinge/gopkgserv/api/request"
	"gitee.com/chuanjinge/gopkgserv/internal/dao"
)

type AnswerItem struct {
	ID           int
	UserSelected []string
}

type SubmitResult struct {
	ExamID     int `json:"examId"`
	Total      int `json:"total"`
	Correct    int `json:"correct"`
	Wrong      int `json:"wrong"`
	Unanswered int `json:"unanswered"`
}

// SubmitAnswers 处理答题提交和统计
func SubmitAnswers(userExamDao *dao.ExamExams, answers []request.SubmitAnswerItem) (*SubmitResult, error) {
	// 查询本次考试所有题目ID
	questionIDs, err := dao.GetQuestionIDsByExamID(userExamDao.ID)
	if err != nil {
		return nil, err
	}

	// 将examId对应的考试结束时间更新为当前时间；考试状态改为已完成
	if err := userExamDao.UpdateExamEndTimeAndStatus(); err != nil {
		return nil, err
	}

	// 查询所有题目详情
	questions, err := dao.GetQuestionsByIDs(questionIDs)
	if err != nil {
		return nil, err
	}
	// 构建答案映射
	answerMap := make(map[int][]string)
	for _, a := range answers {
		answerMap[a.ID] = a.UserSelected
	}
	// 统计
	total := len(questions)
	correct, wrong, unanswered := 0, 0, 0
	for _, q := range questions {
		userAns, ok := answerMap[q.ID]
		var isCorrect *bool
		if !ok || len(userAns) == 0 {
			unanswered++
			isCorrect = nil
		} else {
			// correct_answer 以逗号分隔
			var correctAns []string
			for _, s := range splitAndTrim(q.CorrectAnswer) {
				if s != "" {
					correctAns = append(correctAns, s)
				}
			}
			result := isAnswerCorrect(userAns, correctAns)
			isCorrect = &result
			if result {
				correct++
			} else {
				wrong++
			}
		}
		// 记录到 exam_user_answers 表
		answerStr := ""
		if len(userAns) > 0 {
			answerStr = strings.Join(userAns, ",")
		}
		answerRecord := dao.ExamUserAnswers{
			ExamID:     userExamDao.ID,
			QuestionID: q.ID,
			UserAnswer: answerStr,
			IsCorrect:  isCorrect,
			CreatedAt:  userExamDao.FinishedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:  userExamDao.FinishedAt.Format("2006-01-02 15:04:05"),
		}
		if err := dao.DB.Create(&answerRecord).Error; err != nil {
			// 可选择记录日志或继续
		}
	}
	return &SubmitResult{
		ExamID:     userExamDao.ID,
		Total:      total,
		Correct:    correct,
		Wrong:      wrong,
		Unanswered: unanswered,
	}, nil
}

// splitAndTrim 工具函数
func splitAndTrim(ans string) []string {
	var res []string
	for _, s := range strings.Split(ans, ",") {
		t := strings.TrimSpace(s)
		if t != "" {
			res = append(res, t)
		}
	}
	return res
}

// isAnswerCorrect 判断答案是否正确
func isAnswerCorrect(userAns, correctAns []string) bool {
	if len(userAns) != len(correctAns) {
		return false
	}
	m := make(map[string]struct{})
	for _, a := range userAns {
		m[a] = struct{}{}
	}
	for _, a := range correctAns {
		if _, ok := m[a]; !ok {
			return false
		}
	}
	return true
}
